package cn.bx.bid.ctrl;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Service("roleInterceptor")
public class RoleInterceptor extends HandlerInterceptorAdapter {
    //返回true,放行
    //返回false,终止执行
    @Override//控制器执行之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截了："+handler+"对象");
        //String path=httpServletRequest.getServletPath();
        Object user=request.getSession().getAttribute("USER_LOGIN");
        long startTime = System.nanoTime();
        System.out.println(user);
        request.setAttribute("startTime",startTime);
        if(user==null) {
            //转发
            request.setAttribute("msg","没有权限访问！");
            request.getRequestDispatcher("/login.html").forward(request,response);
            return false;
        }
        return true;
    }

    @Override//控制器执行完成后，视图处理之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("视图名称："+modelAndView.getViewName()+",数据有："+modelAndView.getModelMap());
        long startTime =(long) request.getAttribute("startTime");
        long endtime = System.nanoTime();
        long handlerTime = endtime - startTime;
        double time=handlerTime/1000000000.0;
        System.out.println("完成时间"+time+"秒");
    }

    @Override//视图处理完成后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图解析完成");
    }
}
